#!/usr/bin/env bash

source ../../lib/shell/common.sh
HWTIME=

function get_bios_info() {
    echo -e "\nGet BIOS_boot_mode information:"
    [ -d /sys/firmware/efi ] && echo UEFI || echo BIOS |tee
      if [ $? -ne 0 ]; then
	echo "Failed to get BIOS boot mode info."
		test_fail
      fi

    echo "Get BIOS information:"
    check_types="bios system baseboard processor memory cache"
    for i in $check_types
    do
        sleep 1
        dmidecode -t $i|tee
        [ $? -ne 0 ] && { echo "Failed to obtain BIOS information.";test_fail; }
    done
}

function display_hwclock() {
    echo -e "\nDisplay hwclock information:"
    HWTIME=$(hwclock --show|tee)
    [ $? -ne 0 ] && echo "ERROR:failed to display hwclock" && test_fail
}

function systime_sync2_hwclock() {
    echo -e "\nSynchronize the system time to the hardware time"
    hwclock -w |tee
    [ $? -ne 0 ] && echo "ERROR:Failed to synchronize the system time to the hardware time"  && test_fail
}

function set_hwtime(){
    echo -e "\nSetting hardware Time"
    echo $(date "+%Y-%m-%d %H:%M:%S") | xargs -i  hwclock --set --date {} |tee
    [ $? -ne 0 ] && echo "ERROR:Failed to set hardware time"  && test_fail
}

function hwclock_sync2_systime(){
    echo -e "\nSynchronize the hardware time to the system time"
    hwclock -s |tee
    [ $? -ne 0 ] && echo "ERROR:Failed to synchronize the hardware time to the system time"  && test_fail
}

function hwclock_debugtime(){
    echo -e "\nView hardware time debugging information:"
    hwclock --systohc --debug |tee
    [ $? -ne 0 ] && echo "ERROR:Failed to debug time"  && test_fail
}

function test_time() {
    echo -e "\nTest hardware time"
    hwclock --systz --test --debug |tee
    [ $? -ne 0 ] && echo "ERROR:Failed to test time"  && test_fail
}

function run_biostimer_test() {
    echo "=============run BIOS detection time start================="
    test_time
    hwclock_debugtime

    #Both hardware and system time is based on the latest time
    display_hwclock
    hwtimestr=$(date -d "$HWTIME" +%s |tee)
    systimestr=$(date +%s |tee)
    if [ $(echo "$hwtimestr> $systimestr"|bc -l) -eq 0 ];then
        systime_sync2_hwclock
    else
        hwclock_sync2_systime
    fi
    [ $? -ne 0 ] && set_hwtime
    echo "=============run BIOS detection time end==================="
}

# # # # # # # # # # # # # # main # # # # # # # # # # # #
print_test_info "bios"
get_bios_info
run_biostimer_test
test_pass
